<?
session_start();
header('Content-type: text/html;charset=utf-8');

if ($_SESSION['login']!=true)
{
	header ("Location: index.php",true,301);
    exit();
};

include('../db_info.php');
include 'XML-RPC/RPC.php';


//GET PARTNNER_ROW
$sql="select * from partners where id=".$_SESSION['partner_id']." ";
if(!$result = $GLOBALS['mysqli_conn1']->query($sql))
{
	echo "<br>".$sql;
	exit();
};
	
if (mysqli_num_rows($result)==0)
{
	header ("Location: index.php",true,301);
    exit();
};

$partner_row=mysqli_fetch_array($result);

if (isset($_GET["del"]))
{
	$all_check=true;

	$sql="select * from aliases inner join sites_tbl on aliases.domain_id=sites_tbl.id where aliases.id=".$_GET["del"]." and partner_id=".$_SESSION['partner_id']." ";
	if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
					{
							echo "error:".$sql;
							exit();
						
					};
	if (mysqli_num_rows($result)!=1)		
		{
			$all_check=false;
            $p_rez.=" Неверные данные.";
		};			
		
	if ($all_check)
	{
		$row = mysqli_fetch_array($result);
		$alias_name=$row['alias_name'];
		$domain_name=$row['domain_name'];

		$login_username="aff-pro";
		$login_password="WXvmzuKsdv0jNQmf";

		$cli = new XML_RPC_Client('/cpanel/xmlrpc.php', '212.113.36.21','2580');
		$cli->setCredentials($login_username, $login_password);

		// If you want to turn debugging on...
		//$cli->setDebug(1);

		// If your payload requires extra lines to stay in tact...
		// NOTE: The $remove_extra_lines property was added in Version 1.4.6.
		// $cli->remove_extra_lines = false;

		// If inspect the XML request sent to the server...
		 //$msg->createPayload();
		 //logit($msg->payload);  // Hypothetical function
		 
		 
		function handleResponse($resp) {
			if (!$resp) {
				echo 'Communication error: ' . $cli->errstr;
				exit;
			}
			if (!$resp->faultCode()) {
				return($val = $resp->value());
			} else {
				echo 'Fault Code: ' . $resp->faultCode() . "\n";
				echo 'Fault Reason: ' . $resp->faultString() . "\n";
			}
			return(false);
		}

		if ( !isset($_SESSION['sess_id']) || ( (time() - $_SESSION['mtime']) > 300 ) ) {
			$auth = new XML_RPC_Value(array(
				'username' => new XML_RPC_Value($login_username,'string'),
				'password' => new XML_RPC_Value($login_password,'string')
			),'struct');
			$msg = new XML_RPC_Message('Auth', array($auth));
			$resp = $cli->send($msg);
			if (!($val = handleResponse($resp))) die();

			if ($val->structmem('isAuthed')->scalarval() == 1) {
		//    echo "Access granted";
			$sess_id = $val->structmem('session_id')->scalarval();
			$_SESSION['sess_id'] = $sess_id;
			$_SESSION['mtime'] = time();
			} else {
		//    echo "Access denied"; 
			exit;
			}
		} else {
			$_SESSION['mtime'] = time();
			$sess_id = $_SESSION['sess_id'];
		}



		 $msg = new XML_RPC_Message('CallFunc', array(
									new XML_RPC_Value($sess_id, 'string'), 
									new XML_RPC_Value('delVirtualHostAlias', 'string'), 
									XML_RPC_encode(array($domain_name,$alias_name))
								));
		$resp = $cli->send($msg);
		if (!$resp) {
			echo 'Communication error: ' . $cli->errstr;
			exit;
		}
		if (!$resp->faultCode()) {
			$last_info = "Alias deleted";
			
			$sql="delete from aliases where id=".$_GET["del"]." and partner_id=".$_SESSION['partner_id']." ";
			if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
					{
						echo "error:".$sql;
						exit();
					
					};
			
			
		} else {
			$last_err = 'Fault Code: ' . $resp->faultCode() . "<br />";
			$last_err.= 'Fault Reason: ' . $resp->faultString() . "";
			$p_rez="Ошибка данных!1";
		}




		$msg = new XML_RPC_Message('CallFunc', array(new XML_RPC_Value($sess_id, 'string'), new XML_RPC_Value('closeSession', 'string')));
		$resp = $cli->send($msg);
		handleResponse($resp);
		
	};				
};
//print_r($_POST);
if (isset($_POST["add"]))
{

   $error="";
   if ((isset($_POST["alias_name"]))&&(isset($_POST["domain_id"])))
   {
	//echo "!!!";
		$alias_name=$_POST["alias_name"];	
		$domain_id=$_POST["domain_id"];
		$sid=(int)$_POST["sid"];
		
	
		
							$all_check=true;
							$alias_name=strtolower($alias_name);
                            $alias_name=str_replace("http://www.","",$alias_name);
                            $alias_name=str_replace("http://","",$alias_name);
                            if (($alias_name[0]=="w")&&($alias_name[1]=="w")&&($alias_name[2]=="w")&&($alias_name[3]=="."))
                                 $alias_name=substr($alias_name,4);

                            if (!ereg ("^([a-z0-9\.\-]+\.[a-z]{2,4})$", $alias_name, $regs)) 
                            {
								$all_check=false;
                                $p_rez="Неверный формат: ".$alias_name.".";
                            };
							
		$sql="select * from sites_tbl where id=".$domain_id."  ";
		if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
					{
						echo "error:".$sql;
						exit();
					
					};
		if (mysqli_num_rows($result)!=1)		
		{
			$all_check=false;
            $p_rez.=" Неверные данные.";
		};
		
		$row = mysqli_fetch_array($result);
		$domain_name=$row['domain_name'];
		
		$sql="select * from aliases where alias_name='".$alias_name."' ";
		if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
					{
						echo "error:".$sql;
						exit();
					
					};
		if (mysqli_num_rows($result)==1)		
		{
			$all_check=false;
            $p_rez.=" Такой домен уже используется.";
		};
		
		$sql="select * from sites_tbl where domain_name='".$alias_name."' ";
		if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
					{
						echo "error:".$sql;
						exit();
					
					};
		if (mysqli_num_rows($result)>=1)		
		{
			$all_check=false;
            $p_rez.=" Такой домен уже используется.";
		};
		
		if ($all_check)
		{
			$sql="select count(id) as kol from aliases where partner_id=".$_SESSION['partner_id']." ";
			if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
				{
						echo "error:".$sql;
						exit();
					
				};
			$row = mysqli_fetch_array($result);
			
			if ($row['kol']<120)
			{
				$login_username="aff-pro";
				$login_password="WXvmzuKsdv0jNQmf";

				$cli = new XML_RPC_Client('/cpanel/xmlrpc.php', '212.113.36.21','2580');
				$cli->setCredentials($login_username, $login_password);

				// If you want to turn debugging on...
				//$cli->setDebug(1);

				// If your payload requires extra lines to stay in tact...
				// NOTE: The $remove_extra_lines property was added in Version 1.4.6.
				// $cli->remove_extra_lines = false;

				// If inspect the XML request sent to the server...
				 //$msg->createPayload();
				 //logit($msg->payload);  // Hypothetical function
				 
				//echo "!!!";
				function handleResponse($resp) {
					if (!$resp) {
						echo 'Communication error: ' . $cli->errstr;
						exit;
					}
					if (!$resp->faultCode()) {
						return($val = $resp->value());
					} else {
						echo 'Fault Code: ' . $resp->faultCode() . "\n";
						echo 'Fault Reason: ' . $resp->faultString() . "\n";
					}
					return(false);
				}

				if ( !isset($_SESSION['sess_id']) || ( (time() - $_SESSION['mtime']) > 300 ) ) {
					$auth = new XML_RPC_Value(array(
						'username' => new XML_RPC_Value($login_username,'string'),
						'password' => new XML_RPC_Value($login_password,'string')
					),'struct');
					$msg = new XML_RPC_Message('Auth', array($auth));
					$resp = $cli->send($msg);
					if (!($val = handleResponse($resp))) die();

					if ($val->structmem('isAuthed')->scalarval() == 1) {
				//    echo "Access granted";
					$sess_id = $val->structmem('session_id')->scalarval();
					$_SESSION['sess_id'] = $sess_id;
					$_SESSION['mtime'] = time();
					} else {
				//    echo "Access denied"; 
					exit;
					}
				} else {
					$_SESSION['mtime'] = time();
					$sess_id = $_SESSION['sess_id'];
				}



				 $msg = new XML_RPC_Message('CallFunc', array(
											new XML_RPC_Value($sess_id, 'string'), 
											new XML_RPC_Value('addVirtualHostAlias', 'string'), 
											XML_RPC_encode(array($domain_name,$alias_name))
										));
				$resp = $cli->send($msg);
				if (!$resp) {
					echo 'Communication error: ' . $cli->errstr;
					exit;
				}
				if (!$resp->faultCode()) {
					$last_info = "Alias added";
					
					$sql="insert into aliases(partner_id,domain_id,alias_name,sid) values (".$_SESSION['partner_id'].",'".$domain_id."','".$alias_name."',".$sid.") ";
					//echo $sql;
					if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
								{
									echo "error:".$sql;
									exit();
								
								}; 
					$p_rez="Информация успешно обновлена!";
					
					
				} else {
					$last_err = 'Fault Code: ' . $resp->faultCode() . "<br />";
					$last_err.= 'Fault Reason: ' . $resp->faultString() . "";
					
					$p_rez="Нельзя использовать данный домен!1".$last_err;
				}




				$msg = new XML_RPC_Message('CallFunc', array(new XML_RPC_Value($sess_id, 'string'), new XML_RPC_Value('closeSession', 'string')));
				$resp = $cli->send($msg);
				handleResponse($resp);

			}
			else
			{
				$p_rez="Вы достигли лимита!";
			};
		};	
	};
};

$sql="select *,aliases.id as a_id from  aliases inner join sites_tbl on aliases.domain_id=sites_tbl.id where partner_id=".$_SESSION['partner_id']." order by name,alias_name";
	if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
				{
				    echo "error:".$sql;
					exit();
				
				};
	

	  
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1251"/>
    <title>kz-pro.com - Партнерская программа автострахования</title>
    <link type="text/css" rel="stylesheet" href="style.css"/>
    <!--[if lte IE 7]><link type="text/css" rel="stylesheet" href="ie.css" /><![endif]-->
</head>

<body>
    <div class="insidepage">
        <div id="page">
            <div id="header">
                <h1 class="logo"><a href="#" title="kz-pro.com - Партнерская программа автострахования">kz-pro.com - Партнерская программа автострахования</a></h1>
                <ul class="mainmenu">
                    <li><span><a href="lk.php" title="Личный кабинет">Главная</a></span></li>
                    <li class="active"><span><em>FAQ</em></span></li>
                    <li><span><a href="keys.php" title="База ключевый слов">База ключевый слов</a></span></li>
                    <li><span><a href="support.php" title="Служба поддержки">Служба поддержки</a></span></li>
                    <li class="logout"><span><a href="exit.php" title="Выход">Выход</a></span></li>
                </ul>
                <div class="userinfo">Вы вошли как, <a href="#" title="Wildcat"><?echo $partner_row['login'];?></a></div>
                <form action="#" method="post" class="wmrForm">
                    <h3><span>Web</span>Money</h3>
                    <div class="field clearfix">
                        <em>R</em>
                        <span class="input_text"><span><span><input type="text" value="<?echo substr($partner_row['wmr'],1);?>"/></span></span></span>
                    </div>
                    <p>Автоматические выплаты каждую среду второй и четвертой недель месяца</p>
                    <!--<span class="blueBtn"><span><span><input type="submit" value="Сохранить" /></span></span></span>-->
                </form>
                <div class="news">
                    <h3>Новости</h3>
                    <ul>
                        <li><a href="#" title="Выплаты произведены">Выплаты произведены</a></li>
                        <li><a href="#" title="Новый дизайн сайта">Новый дизайн сайта</a></li>
                        <li><a href="#" title="Информация о VIP скидке">Информация о VIP скидке</a></li>
                        <li class="all_news"><a href="#" title="Все новости">Все новости</a></li>
                    </ul>
                </div>
            </div>
            <div id="content">
			
 <h2>Настройки- парковка доменов</h2><?echo $p_rez;?>

    <br />
		В настройках зоны вашего домена вам необходимо добавить запись 'A' с ip сайта(ip можно узнать, например так - http://pr-cy.ru/whois/site.ru). (Например @	A	 	91.213.175.160)
	</br>
    
<table width="100%" border="0">
  
  <tr><td>
    <table>
		<tr><td><b>Платник</b></td><td><b>Припаркованный домен</b></td><td><b>Удалить</b></td></tr>
		<?
			while($row = mysqli_fetch_array($result))
			{
				echo "<tr><td>".$row['name']."</td><td>".$row['alias_name']."</td><td><a href='?del=".$row['a_id']."'>Удалить</a></td></tr>";
			};
		
		?>
	</table>	
	
	</td></tr>
	<tr><td>
	<br /><br /><br /><br />
    <form action="aliases.php" method="post">
			Платник:<select name="domain_id">
				<?
					$sql="select * from sites_tbl where 1 order by name";
					if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
					{
						echo "error:".$sql;
						exit();
				
					};
					
					while($row = mysqli_fetch_array($result))
					{
						echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
					};
				
				?>
					</select>
			<br />
			Ваш домен:<input type="text" name="alias_name">
			<br />
			sid(для отображения статистики):<select name="sid">
			<?
					$sql="select * from subaccs where partner_id=".$_SESSION['partner_id']." order by name";
					if (!$result = $GLOBALS['mysqli_conn1']->query($sql))
					{
						echo "error:".$sql;
						exit();
				
					};
					
					while($row = mysqli_fetch_array($result))
					{
						echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
					};
				
				?>
			</select>
			<br />
			<input type="submit" name="add" value="Добавить">
	</form>
	
    <br />

  </td></tr>

</table>

    <br />
  
 </div>
        </div>
        <div id="footer_out"><div id="footer">Все права защищены компанией "Kz-pro"</div></div>
    </div>
</body>
</html>